import os
import requests
import tarfile
import shutil


def gateways_upgrade(url):

    tmp_folder = '/tmp/upgrade_tmp'
    target_folder = '/usr/local/src/lora-wan-ns-api'

    try:
        # 创建临时文件夹
        os.makedirs(tmp_folder, exist_ok=True)

        # 下载压缩包到临时文件夹中
        filename = os.path.join(tmp_folder, 'upgrade.tar')
        response = requests.get(url, stream=True)
        with open(filename, 'wb') as file:
            shutil.copyfileobj(response.raw, file)

        # 解压缩文件
        with tarfile.open(filename, 'r') as tar:
            tar.extractall(tmp_folder)

        # 替换目标文件夹内容
        shutil.rmtree(target_folder)
        shutil.copytree(os.path.join(tmp_folder, 'upgrade'), target_folder)

        return 1

        print("基站升级完成")
    except Exception as e:
        print(f"基站升级失败: {e}")
        return 0
    finally:
        # 删除临时文件夹
        shutil.rmtree(tmp_folder)